package com.memorypalace.action;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.memorypalace.deck.biz.NoteBiz;
import com.memorypalace.pojo.Note;
import com.memorypalace.pojo.User;

@Controller
@RequestMapping("/import")
public class ImportAction {

	@Autowired
	private NoteBiz noteBiz;
	
	@RequestMapping("/uploadtxt")
	@ResponseBody
	public void uploadtxt(MultipartFile file,HttpServletRequest request,HttpServletResponse response) throws IOException{
		System.out.println("file:"+file);
		System.out.println("fileContentType:"+file.getContentType());
		System.out.println("fileName:"+file.getName());
		System.out.println("fileSize:"+file.getSize());
		System.out.println("fileOriginalFilename:"+file.getOriginalFilename());
		byte[] bytes = file.getBytes();
		
		System.out.println();
		InputStream is = file.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		char[] buf = new char[1024];
		int length = -1;
		InputStreamReader reader = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(reader);
		Gson gson = new Gson();
		User user = (User) request.getSession().getAttribute("user");
		String userId = user.getUserId();
		while(br.ready()){
			String[] areas = br.readLine().split("\t");
			System.out.println(areas.length);
			String content = gson.toJson(areas);
			// 添加到笔记类型为"基础正反",牌组为"翻译"
			Note note = new Note(null, userId, content, 
					"355980cc-3858-11e7-8e4c-e18a12b866d4", "[\"正面\",\"反面\"]", new Date(), new Date());
			Boolean addResult = noteBiz.addNote(note);
			System.out.println("addResult:"+addResult);
			System.out.println("note:"+note);
		}
//		 while((length=bis.read(buf))!=-1){
//			 String str = new String(buf,0,length);
//			 System.out.println(str);
//		 }
		System.out.println("结束");
	}
}
